from typing import Optional
from math import inf


class TreeNode:

    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


class Solution:

    def sufficientSubset(self, root: Optional[TreeNode],
                         limit: int) -> Optional[TreeNode]:

        def f(root: TreeNode, tot):
            if root.left is None and root.right is None:
                return root.val
            v = root.val
            tot += v

            l = r = -inf
            if root.left is not None:
                l = f(root.left, tot)
                if l + tot < limit:
                    root.left = None
            if root.right is not None:
                r = f(root.right, tot)
                if r + tot < limit:
                    root.right = None
            return v + max(l, r)

        return None if f(root, 0) < limit else root
